import React, { useState, useEffect } from "react";
import {
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  List,
  Checkbox,
  Tag,
  Avatar,
  Divider,
  message,
  Popconfirm,
  Card
} from "antd";
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UserOutlined,
  CalendarOutlined,
  FileTextOutlined
} from "@ant-design/icons";
import { useAppDispatch } from "../../../hooks/redux";
import { updateTask } from "../../../store/projectSlice";
import type { Task, SubTask, TaskCard as TaskCardType } from "../../../types/project";
import { TaskPriority, TaskStatus } from "../../../types/project";
import { mockProjectApi } from "../../../api/mockProjectApi";
import dayjs from "dayjs";

const { TextArea } = Input;
const { Option } = Select;

interface TaskDetailModalProps {
  /** 弹窗是否可见 */
  visible: boolean;
  /** 取消回调 */
  onCancel: () => void;
  /** 任务数据 */
  task: Task;
  /** 项目ID */
  projectId: string;
}

/**
 * 任务详情弹窗组件
 * 显示任务的详细信息，支持编辑、添加子任务和卡片等功能
 */
const TaskDetailModal: React.FC<TaskDetailModalProps> = ({ visible, onCancel, task, projectId }) => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [subTasks, setSubTasks] = useState<SubTask[]>(task.subTasks || []);
  const [cards, setCards] = useState<TaskCardType[]>(task.cards || []);
  const [newSubTaskTitle, setNewSubTaskTitle] = useState("");
  const [newCardTitle, setNewCardTitle] = useState("");
  const [newCardContent, setNewCardContent] = useState("");

  /**
   * 获取用户列表
   */
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userList = await mockProjectApi.getUsers();
        setUsers(userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    };

    if (visible) {
      fetchUsers();
    }
  }, [visible]);

  /**
   * 重置表单数据
   */
  useEffect(() => {
    if (visible && task) {
      form.setFieldsValue({
        title: task.title,
        description: task.description,
        status: task.status,
        priority: task.priority,
        assigneeId: task.assignee?.id,
        startDate: task.startDate ? dayjs(task.startDate) : null,
        dueDate: task.dueDate ? dayjs(task.dueDate) : null,
        milestone: task.milestone,
        tags: task.tags || []
      });
      setSubTasks(task.subTasks || []);
      setCards(task.cards || []);
    }
  }, [visible, task, form]);

  /**
   * 计算任务进度
   * @param subTaskList 子任务列表
   * @returns 进度百分比
   */
  const calculateProgress = (subTaskList: SubTask[]): number => {
    if (subTaskList.length === 0) return 0;
    const completedCount = subTaskList.filter(st => st.completed).length;
    return Math.round((completedCount / subTaskList.length) * 100);
  };

  /**
   * 处理表单提交
   * @param values 表单数据
   */
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const updatedTask = {
        ...values,
        assignee: values.assigneeId ? users.find(u => u.id === values.assigneeId) : undefined,
        startDate: values.startDate?.toISOString(),
        dueDate: values.dueDate?.toISOString(),
        subTasks,
        cards,
        progress: calculateProgress(subTasks)
      };

      await dispatch(
        updateTask({
          projectId,
          taskId: task.id,
          data: updatedTask
        })
      ).unwrap();

      message.success("任务更新成功");
      onCancel();
    } catch (error) {
      console.error("更新任务失败:", error);
      message.error("更新任务失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 添加子任务
   */
  const handleAddSubTask = () => {
    if (!newSubTaskTitle.trim()) {
      message.warning("请输入子任务标题");
      return;
    }

    const newSubTask: SubTask = {
      id: `subtask-${Date.now()}`,
      title: newSubTaskTitle.trim(),
      completed: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    setSubTasks([...subTasks, newSubTask]);
    setNewSubTaskTitle("");
  };

  /**
   * 切换子任务完成状态
   * @param subTaskId 子任务ID
   */
  const handleToggleSubTask = (subTaskId: string) => {
    const updatedSubTasks = subTasks.map(st =>
      st.id === subTaskId ? { ...st, completed: !st.completed, updatedAt: new Date().toISOString() } : st
    );
    setSubTasks(updatedSubTasks);
  };

  /**
   * 删除子任务
   * @param subTaskId 子任务ID
   */
  const handleDeleteSubTask = (subTaskId: string) => {
    setSubTasks(subTasks.filter(st => st.id !== subTaskId));
  };

  /**
   * 添加卡片
   */
  const handleAddCard = () => {
    if (!newCardTitle.trim()) {
      message.warning("请输入卡片标题");
      return;
    }

    const newCard: TaskCardType = {
      id: `card-${Date.now()}`,
      title: newCardTitle.trim(),
      description: newCardContent.trim() || undefined,
      content: newCardContent.trim() || undefined,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    setCards([...cards, newCard]);
    setNewCardTitle("");
    setNewCardContent("");
  };

  /**
   * 删除卡片
   * @param cardId 卡片ID
   */
  const handleDeleteCard = (cardId: string) => {
    setCards(cards.filter(c => c.id !== cardId));
  };

  /**
   * 获取状态选项
   */
  const statusOptions = [
    { value: TaskStatus.NOT_STARTED, label: "未开始", color: "#d9d9d9" },
    { value: TaskStatus.IN_PROGRESS, label: "进行中", color: "#1890ff" },
    { value: TaskStatus.COMPLETED, label: "已完成", color: "#52c41a" }
  ];

  /**
   * 获取优先级选项
   */
  const priorityOptions = [
    { value: TaskPriority.LOW, label: "低优先级", color: "#87d068" },
    { value: TaskPriority.MEDIUM, label: "中优先级", color: "#108ee9" },
    { value: TaskPriority.HIGH, label: "高优先级", color: "#f50" },
    { value: TaskPriority.URGENT, label: "紧急", color: "#ff4d4f" }
  ];

  /**
   * 里程碑选项
   */
  const milestoneOptions = [
    "M0 - 项目启动",
    "M1 - 需求确认",
    "M1 - 技术选型",
    "M2 - 环境搭建",
    "M2 - 设计完成",
    "M3 - 核心功能",
    "M4 - 测试验收",
    "M5 - 上线发布"
  ];

  return (
    <Modal
      title={
        <div className="flex items-center gap-2">
          <EditOutlined />
          <span>任务详情</span>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={() => form.submit()}>
          保存更改
        </Button>
      ]}
      width={800}
      destroyOnClose
    >
      <Form form={form} layout="vertical" onFinish={handleSubmit}>
        {/* 基本信息 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-4">基本信息</h3>

          {/* 任务标题 */}
          <Form.Item
            name="title"
            label="任务标题"
            rules={[
              { required: true, message: "请输入任务标题" },
              { max: 100, message: "标题不能超过100个字符" }
            ]}
          >
            <Input placeholder="请输入任务标题" />
          </Form.Item>

          {/* 任务描述 */}
          <Form.Item name="description" label="任务描述">
            <TextArea placeholder="请输入任务描述" rows={3} showCount maxLength={500} />
          </Form.Item>

          {/* 状态和优先级 */}
          <div className="flex gap-4">
            <Form.Item name="status" label="任务状态" className="flex-1">
              <Select>
                {statusOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    <Tag color={option.color} className="mr-1">
                      {option.label}
                    </Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="priority" label="优先级" className="flex-1">
              <Select>
                {priorityOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    <Tag color={option.color} className="mr-1">
                      {option.label}
                    </Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          {/* 负责人和里程碑 */}
          <div className="flex gap-4">
            <Form.Item name="assigneeId" label="负责人" className="flex-1">
              <Select placeholder="请选择负责人" allowClear>
                {users.map(user => (
                  <Option key={user.id} value={user.id}>
                    <div className="flex items-center gap-2">
                      <Avatar size={20} src={user.avatar} icon={<UserOutlined />} />
                      {user.name}
                    </div>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="milestone" label="里程碑" className="flex-1">
              <Select placeholder="请选择里程碑" allowClear>
                {milestoneOptions.map(milestone => (
                  <Option key={milestone} value={milestone}>
                    {milestone}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          {/* 时间设置 */}
          <div className="flex gap-4">
            <Form.Item name="startDate" label="开始时间" className="flex-1">
              <DatePicker className="w-full" format="YYYY-MM-DD" />
            </Form.Item>

            <Form.Item name="dueDate" label="截止时间" className="flex-1">
              <DatePicker className="w-full" format="YYYY-MM-DD" />
            </Form.Item>
          </div>

          {/* 标签 */}
          <Form.Item name="tags" label="标签">
            <Select mode="tags" placeholder="输入标签，按回车添加" tokenSeparators={[","]} maxTagCount={5} />
          </Form.Item>
        </div>

        <Divider />

        {/* 子任务管理 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-4">
            子任务 ({subTasks.filter(st => st.completed).length}/{subTasks.length})
          </h3>

          {/* 添加子任务 */}
          <div className="flex gap-2 mb-4">
            <Input
              placeholder="输入子任务标题"
              value={newSubTaskTitle}
              onChange={e => setNewSubTaskTitle(e.target.value)}
              onPressEnter={handleAddSubTask}
              className="flex-1"
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddSubTask}>
              添加
            </Button>
          </div>

          {/* 子任务列表 */}
          <List
            dataSource={subTasks}
            renderItem={subTask => (
              <List.Item
                actions={[
                  <Popconfirm
                    title="确定要删除这个子任务吗？"
                    onConfirm={() => handleDeleteSubTask(subTask.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="text" icon={<DeleteOutlined />} danger size="small" />
                  </Popconfirm>
                ]}
              >
                <div className="flex items-center gap-2 flex-1">
                  <Checkbox checked={subTask.completed} onChange={() => handleToggleSubTask(subTask.id)} />
                  <span className={subTask.completed ? "line-through text-gray-500" : ""}>{subTask.title}</span>
                </div>
              </List.Item>
            )}
            locale={{ emptyText: "暂无子任务" }}
          />
        </div>

        <Divider />

        {/* 卡片管理 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-4">卡片 ({cards.length})</h3>

          {/* 添加卡片 */}
          <div className="space-y-2 mb-4">
            <Input placeholder="输入卡片标题" value={newCardTitle} onChange={e => setNewCardTitle(e.target.value)} />
            <TextArea
              placeholder="输入卡片内容（可选）"
              value={newCardContent}
              onChange={e => setNewCardContent(e.target.value)}
              rows={2}
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddCard}>
              添加卡片
            </Button>
          </div>

          {/* 卡片列表 */}
          <div className="space-y-3">
            {cards.map(card => (
              <Card
                key={card.id}
                size="small"
                title={
                  <div className="flex items-center gap-2">
                    <FileTextOutlined />
                    {card.title}
                  </div>
                }
                extra={
                  <Popconfirm
                    title="确定要删除这个卡片吗？"
                    onConfirm={() => handleDeleteCard(card.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="text" icon={<DeleteOutlined />} danger size="small" />
                  </Popconfirm>
                }
              >
                {card.content && <p className="text-sm text-gray-600 whitespace-pre-wrap">{card.content}</p>}
                <div className="text-xs text-gray-400 mt-2">
                  创建于 {dayjs(card.createdAt).format("YYYY-MM-DD HH:mm")}
                </div>
              </Card>
            ))}
            {cards.length === 0 && <div className="text-center text-gray-500 py-4">暂无卡片</div>}
          </div>
        </div>

        {/* 任务信息 */}
        <Divider />
        <div className="text-sm text-gray-500 space-y-1">
          <div className="flex items-center gap-2">
            <UserOutlined />
            <span>创建者: {task.creator.name}</span>
          </div>
          <div className="flex items-center gap-2">
            <CalendarOutlined />
            <span>创建时间: {dayjs(task.createdAt).format("YYYY-MM-DD HH:mm")}</span>
          </div>
          <div className="flex items-center gap-2">
            <CalendarOutlined />
            <span>更新时间: {dayjs(task.updatedAt).format("YYYY-MM-DD HH:mm")}</span>
          </div>
        </div>
      </Form>
    </Modal>
  );
};

export default TaskDetailModal;
